from serial_manage import SerialManage


class BccControl():
    def __init__(self, port = "COM10"):
        self.bcc_ser = SerialManage(port=port)

    def connect_serial(self):
        self.bcc_ser.connect_serial()

    def disconnect_serial(self):
        self.bcc_ser.close_serial()

    def start_device(self):
        self.bcc_ser.write(bytearray([0x55,0x00,0x02,0x00,0x00,0x57]))
        return self.deal_count()

    def stop_device(self):
        self.bcc_ser.write(bytearray([0x55,0x01,0x02,0x00,0x00,0x58]))
        return self.deal_count()

    def clear_count(self):
        self.bcc_ser.write(bytearray([0x55,0x02,0x02,0x00,0x00,0x59]))
        return self.deal_count()

    def start_count(self, count):
        high_8bit, low_8bit = self.split_decimal_to_high_low(int(count))
        last = 0x55+0x33+0x2+high_8bit+low_8bit
        last = self.get_low_eight_bits_as_decimal(last)
        self.bcc_ser.write(bytearray([0x55,0x03,0x02,high_8bit,low_8bit,last]))
        return self.deal_count()

    def get_count(self):
        self.bcc_ser.write(bytearray([0x55,0x04,0x02,0x00,0x00,0x5B]))
        return self.deal_count()

    def deal_count(self):
        data = self.bcc_ser.read_queue.get()
        print(data)
        return self.convert_data_to_decimal(data)

    @staticmethod
    def split_decimal_to_high_low(decimal_number):
        """
        将十进制数转换为16位二进制数，分别返回高8位和低8位的十进制数。

        :param decimal_number: 输入的十进制数
        :return: (高8位的十进制数, 低8位的十进制数)
        """
        # 转换为二进制并补齐为16位
        binary_representation = bin(decimal_number)[2:].zfill(16)

        # 分割为高8位和低8位
        high_eight_bits = binary_representation[:8]
        low_eight_bits = binary_representation[8:]

        # 分别转换为十进制数
        high_decimal = int(high_eight_bits, 2)
        low_decimal = int(low_eight_bits, 2)

        return high_decimal, low_decimal

    @staticmethod
    def get_low_eight_bits_as_decimal(decimal_number):
        """
        将十进制数转换为二进制后取低八位，并返回对应的十进制数。

        :param decimal_number: 输入的十进制数
        :return: 低八位对应的十进制数
        """
        # 转换为二进制并去掉前缀 '0b'
        binary_representation = bin(decimal_number)[2:]

        # 取低八位（不足8位时前面补0）
        low_eight_bits = binary_representation[-8:].zfill(8)

        # 转换低八位为十进制数
        return int(low_eight_bits, 2)

    @staticmethod
    def convert_data_to_decimal(data:str):
        # 提取低八位（第3和第4位）和高八位（第5和第6位）
        hex_value = data[7:10]
        # 转换为十进制数
        decimal_value = int(hex_value, 16)

        return decimal_value

if __name__ == '__main__':
    print(BccControl.convert_data_to_decimal('5504000177d1'))